<template>
  <div>
    <div class="row-main" :style="{'overflow-x':$store.state.app.screenWidth<500?'scroll':'auto'}">
      <el-button type="shenda" size="small" icon="el-icon-plus" @click="agentKeyAdd()" v-preventReClick>增加API账户</el-button>
      <el-table
        :header-cell-style="{ 'background':$store.state.app.tableBgColor,'color':'#606266' }"
        :data="tableData"
        ref="table"
        tooltip-effect="dark"
        class="row-main-table"
        v-loading.fullscreen="tableLoading"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.2)"
        @sort-change="changeSort"
      >
        <el-table-column
          prop="keyName"
          label="API账户"
          align="center"
          :fixed="$store.state.app.screenWidth<992?true:false"
          :width="$store.state.app.screenWidth<992?'130px':'auto'"
        >
        </el-table-column>
        <el-table-column
          prop="password"
          label="API密码"
          align="center"
          :width="$store.state.app.screenWidth<992?'130px':'auto'">
        </el-table-column>
        <el-table-column
          label="操作"
          align="center">
          <template slot-scope="scope">
            <el-dropdown trigger="click">
              <div class="el-dropdown-link">
                <svg-icon class="el-dropdown-link" icon-class="operation"></svg-icon>
              </div>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>
                  <el-button class="operation" type="text" @click="agentKeyDelete(scope.row)">删除</el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button class="operation" type="text" @click="whitelistAdd(scope.row)" v-preventReClick>
                    配置白名单
                  </el-button>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <div :style="{'overflow-x': $store.state.app.screenWidth<992?'scroll':'none'}">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :page-count='maxPage'
          :total="totalPage"
          :page-sizes="[10,20,50,100]"
          background
          class="row-main-pager"></el-pagination>
      </div>
      <!--设置白名单弹框-->
      <el-dialog
        title="配置白名单"
        top="33vh"
        :visible.sync="whiteDialog"
        :width="$store.state.app.screenWidth<500?'100%':'500px'"
        :append-to-body="true">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="80px" class="demo-ruleForm">
          <el-form-item
            v-for="(item, index) in ruleForm.list"
            :label="'IP' + index"
            :key="index"
            :prop="'list.' + index + '.ip'"
            :rules="{
                required: true, message: '域名不能为空', trigger: 'blur'
            }"
          >
            <el-input v-model="item.ip" style="width: 330px"> <el-button slot="append" icon="el-icon-delete" @click.prevent="removeDomain(item)"></el-button></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
            <el-button @click="addIP" v-show="ruleForm.list&&ruleForm.list.length<10" type="success" plain>新增域名</el-button>
            <el-button @click="resetForm('ruleForm')" type="info" plain>重置</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <!--设置实名弹框-->
      <el-dialog
        class="delete"
        top="33vh"
        :visible.sync="agentKeyDialog"
        :width="$store.state.app.screenWidth<500?'100%':'600px'"
        :append-to-body="true">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="API账户" prop="keyName">
            <el-input size="small" v-model="ruleForm.keyName" style="width:85%"></el-input>
          </el-form-item>
          <el-form-item label="API密码">
            <el-input size="small" v-model="ruleForm.password" style="width:59%;margin-right: 6px" disabled></el-input>
            <el-button type="shenda" size="small" @click="toPassword()">重新生成密码</el-button>
          </el-form-item>
          <el-form-item>
            <el-button size="small" @click="agentKeyDialog = false">取 消</el-button>
            <el-button size="small" type="primary" @click="agentKeySave('ruleForm')" v-preventReClick>确 定</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>


</template>

<script>
  import {mapGetters} from 'vuex'
  import {
    agentKeySave, agentKeyList, agentKeyDelete, IpList, IpDelect, IpSave

  } from '@/api/getData'

  export default {
    name: 'Home',
    data() {
      return {
        value: 'false',
        ruleForm: {
          password: '',
          keyName: '',
          name: '',
          list: [],
        },
        rules: {
          keyName: [
            {required: true, message: '请输入API账户', trigger: 'blur'},
            {min: 5, max: 10, message: '长度在 5 到 10 个字符', trigger: 'blur'}
          ],
        },

        startCardNumber: '',
        endCardNumber: '',
        dialogVisible: false,
        agentKeyDialog: false,
        whiteDialog: false,
        dialogVisible3: false,
        textarea1: '',
        radio2: '1',
        maxPage: 1,
        totalPage: 0,
        tableData: [],
        ascs: [],
        descs: [],
        pageSize: 10,
        currentPage: 1,
        id: '',
        insertTime: '',
        pid: '',
        dictDisabledCardStatus: '',
        dictDisabledCardStatusName: '',
        startCardNum: '',
        endCardNum: '',
        oprationEmp: '',
        oprationEmpName: '',
        dictOprationType: '',
        ruleTypeId: '',
        reason: '',
        oemId: '',
        startTime: '',
        endTime: '',
        ruleName: '',
        input: '',
        dictDisabledRuleType: '',
        dialogVisible1: false,
        tableLoading: false,
        value1: '',
        value2: '',
        inputIp1: '',
        inputIp2: '',
        inputIp3: '',
        idInputHidden1: '',
        idInputHidden2: '',
        idInputHidden3: '',
        agentKeyId: '',
        pagekey: '',
      }
    },

    created() {
      this.agentKeyList()
    },
    methods: {
      async agentKeyAdd() {
        this.pagekey = await this.$getPageKey();
        this.agentKeyDialog = true;
        this.ruleForm.keyName = '';
        this.toPassword();
      },
      toPassword() {
        var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
        var maxPos = $chars.length;
        var pwd = '';
        for (var i = 0; i < 16; i++) {
          var p = $chars.charAt(Math.floor(Math.random() * maxPos))
          pwd = pwd + p;
        }
        this.ruleForm.password = pwd
      },
      //保存账号
      async agentKeySave(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$refs[formName].validate((valid) => {
              if (valid) {
                this.agentKeySave1()
              } else {
                return false;
              }
            });
          } else {
            return false;
          }
        });
      },
      async agentKeySave1() {
        let s = await agentKeySave({
          keyName: this.ruleForm.keyName,
          password: this.ruleForm.password
        })
        if (s._result) {
          this.$message.success("操作成功！")
          this.agentKeyDialog = false;
          this.agentKeyList()
        }
      },
      //删除账户
      async agentKeyDelete(card) {
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          let s = await agentKeyDelete({
            id: card.id,
          })
          if (s._result) {
            this.$message.success("操作成功！")
            this.agentKeyList()
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });

      },
      async whitelistAdd(agentKey) {
        this.agentKeyId = agentKey.id
        this.pagekey = await this.$getPageKey();
        let s = await IpList({
          agentKeyId: agentKey.id,
        })
        this.ruleForm.list = [];
        if (s._result&&s.data&&s.data.length>0) {
          for(let item of s.data){
            this.ruleForm.list.push({ ip: item.ip, id: item.id, })
          }
        }
        else{
          this.addIP()
        }
        this.whiteDialog = true;
      },
      //配置白名单
      submitForm(formName) {
        this.$refs[formName].validate(async (valid) => {
          if(valid){
             let s = await IpSave({
               whiteIpAddresslist: this.ruleForm.list,
               agentKeyId: this.agentKeyId,
               pagekey: this.pagekey
             })
             if(s._result){
               this.$message.success('操作成功');
               this.whiteDialog = false;
             }
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
        this.ruleForm.list = [{
          ip: '',
          id: '',
          agentKeyId: this.agentKeyId,
        }];
      },
      removeDomain(item) {
        var index = this.ruleForm.list.indexOf(item)
        if (index !== -1) {
          this.ruleForm.list.splice(index, 1)
        }
        console.log(this.ruleForm.list)
      },
      addIP() {
        this.ruleForm.list.push({
          ip: '',
          id: '',
        });
      },
      changeSort(column) {
        if (column.order == 'ascending') {
          this.descs = []
          this.ascs = [column.prop];
        } else {
          this.ascs = []
          this.descs = [column.prop];
        }
        this.agentKeyList();
      },

      handleSizeChange(val) {
        this.pageSize = val
        this.agentKeyList()
      },
      handleCurrentChange(val) {
        //console.log(`当前页: ${val}`)
        this.currentPage = val
        this.agentKeyList()
      },

      // 账号列表
      async agentKeyList() {
        this.tableLoading = true;
        const returnData = await agentKeyList({
            page: {
              current: this.currentPage + '',
              size: this.pageSize + '',
              ascs: this.ascs,
              descs: this.descs
            }
          },
          {
            obj: this,
            key: 'tableLoading'
          });
        this.tableData = [];
        if (returnData._result) {
          this.tableLoading = false
          this.maxPage = Math.ceil(returnData.data.total / this.pageSize) // 分页的最大页数
          this.totalPage = returnData.data.total;
          // 数据回显
          returnData.data.records.map(item => {
            const obj = {}
            obj.id = item.id
            obj.keyName = item.keyName   //账号
            obj.password = item.password  //密码
            this.tableData.push(obj)
          })
          this.tableLoading = false
        }
      },
    },
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .disabledList-title {
    font-weight: bold;
    font-size: 14px;
    color: #606266;
    margin-right: 10px;
  }

  .disabledList-tableTitle {
    font-weight: bold;
    color: #606266;
  }

  .block {
    text-align: right;
    margin-top: 20px;
  }

  .el-dropdown-link {
    font-size: 20px;
    cursor: pointer;
  }

  .el-popper[x-placement^=bottom] {
    margin-right: -25px;
    box-shadow: 0px 0px 10px #888888;
    margin-left: 7px;

    .operation {
      border: 0;
      outline: none;
      display: block;
      text-align: center;
      margin: 0;
    }
  }
</style>
